import axios from 'axios';
import moment from 'moment';


const BASE_URL = 'http://api.kgps.vip';


let token = '';
let expiredTime = moment();



async function login() {
    if (token && moment().isBefore(expiredTime)) {
        return true;
    }
    let url = `${BASE_URL}/user/login`;
    let data = {
        loginName: 'baotou535',
        password: 'baotou535'
    };
    try {
        let res = await axios.post(url, data);
        console.log(res.data);
        token = res.data.data.token;
        return true;
    } catch (error) {
        console.error('登陆出错', error.message);
    }
    return false;
}

async function getVehicleStatus(plateNos) {
    let loginRes = await login();
    if (!loginRes) {
        return;
    }
    let url = `${BASE_URL}/vehicle/status`;
    let headers = {
        token: token,
        'Content-Type': 'multipart/form-data'
    };
    let form = new FormData();
    form.append('plateNos', plateNos);
    
    try {
        let response = await axios.post(url, form, { headers: headers });
        console.log(response.data);
        if(response.data.status=true){
            console.log('车辆状态:', response.data.data[0].status);
            return   response.data.data[0];
        }else{
            console.log('获取车辆状态出错:', response.data.code);
            return {err: response.data.code};
        }
    } catch (error) {
        console.error('getVehicleStatus出错', error.message);
        return {err: error.message};
    }
}

/**
 * 获取车辆指定时间段的轨迹
 * @param {*} plateNos
 * @param {*} startTime
 * @param {*} endTime
 * @returns 
 */
async function getVehicelTrajectory(plateNo, startTime, endTime) {
    let loginRes = await login();
    if (!loginRes) {
        return;
    }
    let url = `${BASE_URL}/gps/search?plateNo=${plateNo}&startTime=${startTime}&endTime=${endTime}`;
    let headers = {
        token: token,
    };
    try {
        let response = await axios.get(url,  { headers: headers });
        console.log(response.data);
        if(response.data.status=true){
            console.log('车辆轨迹:', response.data.data);
            return   response.data.data;
        }else{
            console.log('获取车辆轨迹出错:', response.data.code);
            return {err: response.data.code};
        }
    } catch (error) {
        console.error('getVehicelTrajectory出错',url, error.message);
        return {err: error.message};
    }
}

async function test() {
    let plate = '蒙B589AJ';
    let startTime = moment().subtract(1, 'days').valueOf();
    let endTime = moment().valueOf();
    let res = await getVehicelTrajectory(plate, startTime, endTime);
    console.log(res);
}

test();

